<template>
	<div>
		<FormItems
			ref="form"
			v-model="formData"
			:form="formList"
			:state="state"
			labelWidth="100px"></FormItems>
	</div>
</template>

<script>
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import FormItem from '@/views/finance/reimburs/formItem/index.vue';
	import * as apis from '@/api/quota/forecast/edit/api.js';
	export default {
		components: { FormItems },
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
		},
		dicts: ['quota_operation_type'],
		inject: ['details_forecast', 'details_config', 'deptList', '_index', '_currentFormData'],
		data() {
			return {
				dictList: {
					fuelType: [],
				},
			};
		},
		beforeDestroy() {
			if (this.notEmpty(this.details?.productList?.[this.index])) {
				this.$refs.form?.form_resetFields?.();
			}
		},
		computed: {
			config() {
				return this.details_config();
			},
			currentFormData() {
				return this._currentFormData();
			},
			details() {
				return this.details_forecast();
			},
			index() {
				return this._index();
			},
			formData: {
				get() {
					return this.useVModel.call(this);
				},
				set(val) {
					this.$emit('input', val);
				},
			},
			formList() {
				// details.carType 1 新车，2旧车
				// details.carSourceType 1 采购，2现有，3外部
				return [
					{
						label: '选择车辆',
						prop: 'carId',
						propLabel: 'carModelName',
						type: 'select_dialog',
						selectDialogParams: {
							type: 'car',
							title: '请选择车辆',
							params: {
								quotationProductSchemeId: this.details?.schemeId,
								businessType: 7,
								carLockType: 2,
							},
						},
						rules: true,
						selectDialogValidate: row => {
							if (!this.details?.schemeId) {
								this.$message({
									message: '请选择产品方案',
									type: 'warning',
								});
								return false;
							}
							return true;
						},
						cb: res => {
							this.$emitter.emit(
								'initInputState',
								this.currentFormData.sequenceNumber,
							);
							this.$emitter.emit(
								'initCalcData',
								this.currentFormData?.sequenceNumber,
							);
							this.setCarData(res);
						},
						event: {
							type: 'clear',
							cb: row => {
								this.$emitter.emit(
									'initInputState',
									this.currentFormData.sequenceNumber,
								);
								this.$emitter.emit(
									'initCalcData',
									this.currentFormData?.sequenceNumber,
								);
								this.formData.carId = undefined; //车辆id
								this.formData.operationType = undefined; //车辆使用性质
								this.formData.carPlateNo = undefined; //车牌号
								this.formData.carModelId = undefined; //车型id
								this.formData.carModelName = undefined; //车型
								this.formData.carBrandName = undefined; //品牌
								this.formData.carBrandId = undefined; //品牌id
								this.formData.carSeriesName = undefined; //车系
								this.formData.carSeriesId = undefined; //车系id
								this.formData.carSeating = undefined; // 座位数
								this.formData.carSeatingType = undefined;
								this.formData.carCc = undefined; // 排量
								this.formData.carTypeStr = undefined;
								this.formData.carPowerTypeStr = undefined;
								this.formData.carManufacturer = undefined; // 厂商
								this.formData.carGuidePrice = undefined;
								this.formData.carMileage = undefined; // 公里
								this.formData.carPropertyCity = undefined; // 产权城市
								this.formData.carFirstRegistrationDate = undefined; // 首次登记日期
								this.formData.carPurchasePriceQuondam = undefined; // 原新车采购价
								this.formData.carLossFrequence = undefined;
								this.formData.interiorColor = undefined; // 内饰颜色
								this.formData.appearanceColor = undefined; //外观颜色
								this.currentFormData.carCalcCityKey = undefined;
								this.$nextTick(() => {
									this.$emit('getDecorationList');
								});
							},
						},
					},
					{
						label: '车牌号',
						prop: 'carPlateNo',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车辆种类',
						prop: 'carTypeStr',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车辆类型',
						prop: 'carPowerTypeStr',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '品牌',
						prop: 'carBrandName',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车系',
						prop: 'carSeriesName',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车型',
						prop: 'carModelName',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '厂商',
						prop: 'carManufacturer',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '座位',
						prop: 'carSeating',
						type: () => {
							if (/(\-|\/)/g.test(this.formData.carSeatingType)) {
								return 'select';
							}
							return 'input_number';
						},
						state:
							this.type == 'preview'
								? 'readonly'
								: this.showCarSeatSelect
								? 'write'
								: 'disabled',
						selectList: row => {
							if (!this.formData?.carSeatingType) {
								return [];
							}
							if (this.formData.carSeatingType.indexOf('/') !== -1) {
								return this.formData.carSeatingType?.split('/');
							}
							if (this.formData.carSeatingType.indexOf('-') !== -1) {
								let arr = this.formData.carSeatingType?.split('-');
								if (arr?.length < 2) return [];
								let start = arr?.[0] ?? 1;
								let end = arr?.[1];
								let seat = [];
								for (let index = start; index <= end; index++) {
									seat.push(index);
								}
								return seat;
							}
						},
						rules: true,
						event: {
							type: 'change',
							cb: () => {
								this.$emit('getDecorationList');
							},
						},
					},
					{
						label: '排量',
						prop: 'carCc',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '车辆使用性质',
						prop: 'operationType',
						type: 'select',
						selectList: this.dict.type.quota_operation_type,
						rules: true,
					},
					{
						label: '原新车采购价',
						prop: 'carPurchasePriceQuondam',
						tag: 'price',
						type: 'text',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '首次登记日期',
						prop: 'carFirstRegistrationDate',
						type: 'text',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '已行驶公里数',
						prop: 'carMileage',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '产权城市',
						prop: 'carPropertyCity',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
					{
						label: '所属公司',
						prop: 'carAffiliationKey',
						type: 'select',
						selectList: this.deptList.company,
						selectLabel: 'deptName',
						selectValue: 'deptId',
						rules: [
							{
								required: true,
								message: '请选择所属公司',
								trigger: 'change',
							},
						],
						event: {
							type: 'change',
							cb: row => {
								let item = this.deptList.company.find(
									e => e.deptId == row.carAffiliationKey,
								);
								if (item) {
									this.formData.carAffiliationVal = item.deptName;
								}
							},
						},
					},
					{
						label: '运营城市',
						prop: 'carOperateCityVal',
						type: 'input',
						rules: [
							{
								required: true,
								message: '请选择运营城市',
								trigger: 'change',
							},
						],
					},
					{
						label: '当期评估价',
						prop: 'carCurrentAppraisal',
						type: 'input_number',
						tag: 'price',
						rules: [
							{
								required: true,
								message: '请输入当期评估价',
								trigger: 'change',
							},
						],
					},
					{
						label: '到期残值',
						prop: 'carSurplusAppraisal',
						type: 'input_number',
						tag: 'price',
						rules: true,
					},
					{
						label: 'GPS费用',
						prop: 'gpsFee',
						type: 'input_number',
						rules: true,
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						state:
							this.type == 'preview'
								? 'readonly'
								: this.config?.quotationProductSchemeRule?.openGpsModification == 1
								? 'write'
								: 'disabled',
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.gpsFee)) {
									this.currentFormData.planConf.gpsFee_state = 'changed';
								} else {
									this.currentFormData.planConf.gpsFee_state = '';
								}
							},
						},
					},
					{
						label: '年检费（年）',
						prop: 'annualCheckFee',
						type: 'input_number',
						state: 'readonly',
						tag: 'price',
					},
					{
						label: '3年内出险次数',
						prop: 'carLossFrequence',
						type: 'input',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
					},
				];
			},
			showCarSeatSelect() {
				return /(\-|\/)/g.test(this.formData.carSeatingType);
			},
		},
		async created() {
			await this.getFuelType();
		},
		mounted() {},
		methods: {
			getPrevInsurance(car) {
				if (!car.carId) return;
				let params = { carId: car.carId };
				apis.LastInsuranceMoney(params).then(res => {
					console.log(res);

					if (res.code == 200) {
						// 交强险测算金额
						this.currentFormData.insuranceCompulsoryPrevAmount =
							res.data.compulsoryTotalMoney;
						// 车船税测算金额
						this.currentFormData.insuranceCarvesselPrevAmount =
							res.data.carTaxTotalMoney;
						// 商业险测算金额
						this.currentFormData.insuranceCommercialPrevAmount =
							res.data.commercialTotalMoney;

						// 交强险测算金额
						this.currentFormData.insuranceCompulsoryCurrentAmount =
							res.data.compulsoryTotalMoney;

						this.currentFormData.planConf.insuranceCompulsoryCurrentAmount_state =
							'changed';
						// 车船税测算金额
						this.currentFormData.insuranceCarvesselCurrentAmount =
							res.data.carTaxTotalMoney;

						this.currentFormData.planConf.insuranceCarvesselCurrentAmount_state =
							'changed';

						// 商业险测算金额
						this.currentFormData.insuranceCommercialCurrentAmount =
							res.data.commercialTotalMoney;

						this.currentFormData.planConf.insuranceCommercialCurrentAmount_state =
							'changed';
					}
				});
			},
			async getFuelType() {
				this.dictList.fuelType = await this._getDicts('fuel_type');
			},
			getDictLabel(key, dictList) {
				let item = dictList?.find(e => e.dictValue?.toString() == key?.toString());
				return item?.dictLabel;
			},
			setCarData(res, row) {
				console.log(res);
				this.formData.interiorColor = res.interiorColor; // 内饰颜色
				this.formData.appearanceColor = res.exteriorColor; //外观颜色
				this.formData.carId = res.carId; //车辆id
				this.formData.carPlateNo = res.carNo; //车牌号
				this.formData.carVinNo = res.vinNo; // 车架号
				this.formData.operationType = res.carNature; //车辆使用性质
				this.formData.carModelId = res.modelId; //车型id
				this.formData.carModelName = res.modelName; //车型
				this.formData.carBrandName = res.brandName; //品牌
				this.formData.carBrandId = res.brandId; //品牌id
				this.formData.carSeriesName = res.seriesName; //车系
				this.formData.carSeriesId = res.seriesId; //车系id
				this.formData.carSeatingType = res.seatNum;
				if (/(\-|\/)/g.test(res.seatNum)) {
					this.formData.carSeating = undefined; // 座位数
				} else {
					this.formData.carSeating = res.seatNum; // 座位数
				}

				this.formData.carCc = res.liter; // 排量
				this.formData.carTypeStr = res.vehicleCategory; // 车辆种类
				// this.formData.carPowerTypeStr = this.getDictLabel(
				//     res.fuelType,
				//     this.dictList.fuelType
				// ); // 车辆类型
				this.formData.carPowerTypeStr = res.isGreen == 1 ? '新能源车' : '燃油车'; // 车辆类型
				this.formData.carManufacturer = res.makerName; // 厂商
				let price = this.toNumberRide(res.price, 10000);
				this.formData.carGuidePrice = Number.isFinite(price) // 厂商指导价
					? price
					: 0;
				this.formData.isGreen = res.isGreen; // 是否新能源
				this.formData.carMileage = res.returnMileage; // 还车公里
				this.formData.carPropertyCity = res.propertyRightName; // 产权城市
				// propertyRightId 产权城市
				// 上牌城市ID

				// if (this.Empty(this.currentFormData.carLicenseCityKey)) {
				if (true) {
					// 上牌城市
					this.currentFormData.carLicenseCityKey = res.propertyRightId;
					// 开发城市
					this.currentFormData.carAffiliationKey = res.propertyRightId;
					let item = this.deptList.company.find(e => e.deptId == res.propertyRightId);

					if (item) {
						// 上牌城市
						this.currentFormData.carLicenseCityVal = item.deptName;
						let regionId = item.regionId.split('/');
						this.currentFormData.carCalcCityKey = regionId?.[1];
						// 开发城市
						this.currentFormData.carAffiliationVal = item?.deptName;
					}
				}
				this.formData.carFirstRegistrationDate = res.registerTime; // 首次登记日期
				this.formData.carPurchasePriceQuondam = res.purchasePrice; // 原新车采购价
				// this.formData.carMileage = res. // 3年内出险次数
				this.getInsCount(res.carId);
				if (res.isGreen == 1) {
					this.$emitter.emit(
						'setInsuranceCarvesselCurrentAmount',
						this.currentFormData.sequenceNumber,
					);
				}
				this.getPrevInsurance(res);
				// this.getLastMileage(res);
				this.$emit('getDecorationList');
			},
			getLastMileage(car) {
				if (!car.carId) return;
				apis.LastMileage(car.carId).then(res => {
					if (res.code == 200) {
						// 公里数
						this.formData.carMileage = res.data.inboundMileage;
					}
				});
			},
			// 获取三年出现次数
			getInsCount(carId) {
				if (!carId) return;
				apis.CarCount(carId).then(res => {
					if (res.code == 200) {
						this.formData.carLossFrequence = res.data;
					}
				});
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (Object.prototype.toString.call(ref) == '[object Array]') {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(ref, 'form_validate');
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(ref, 'form_validate');
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		margin: 20px;
		padding: 20px;
		border-radius: 8px;
		background-color: #fff;
		.title {
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 22px;
			padding-bottom: 15px;
			border-bottom: 1px solid #e9e9e9;
		}
	}
</style>
